import {
	useAppsStore
} from '@/stores/modules/app.js'
export async function getAddress(isHighAccuracy = false) {
	const useStore = useAppsStore()
	const {
		setLocation
	} = useStore
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: 'scope.userLocation',
			success() { //1.1 允许授权
				resolve(setAddress(isHighAccuracy))
			},
			fail() { //1.2 拒绝授权
				uni.showModal({
					title: '获取不到您的定位',
					content: '允许使用您的定位,以获取准确的活动信息',
					confirmText: "确认",
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting({
								success: (res) => {
									uni.authorize({
										scope: 'scope.userLocation',
										success() { //1.1 允许授权
											resolve(setAddress(
												isHighAccuracy
											))
										},
										fail() {
											setLocation({
												longitude: '',
												latitude: ''
											}).then(result => {
												resolve(
													result
												)
											}).catch(err => {
												reject(err)
											})
										}
									})
								}
							})
						} else {
							setLocation({
								longitude: '',
								latitude: ''
							}).then(result => {
								resolve(
									result
								)
							}).catch(err => {
								reject(err)
							})
						}
					},
					fail: (err) => {
						setLocation({
							longitude: '',
							latitude: ''
						}).then(result => {
							resolve(
								result
							)
						}).catch(err => {
							reject(err)
						})
					}
				})
				return false;
			}
		})
	})
}

export async function setAddress(isHighAccuracy = false) {
	const useStore = useAppsStore()
	const {
		setLocation
	} = useStore
	return new Promise(async (resolve, reject) => {
		uni.getLocation({
			type: 'gcj02',
			isHighAccuracy,
			highAccuracyExpireTime: 4000,
			success: async (res) => {
				setLocation(res).then(result => {
					resolve(
						result
					)
				}).catch(err => {
					reject(err)
				})
			},
			fail: (err) => {
				setLocation({
					longitude: '',
					latitude: ''
				}).then(result => {
					resolve(
						result
					)
				}).catch(err => {
					reject(err)
				})
			}
		});
	})
}